package com.mjk.common.core.rmq.mq;


import com.mjk.common.core.rmq.EventErrorCode;
import com.mjk.common.util.MDCUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import java.lang.management.ManagementFactory;
/**
 * 
* @author mjk  
* @date 2019年3月8日
 */
public class PublishProxy {
	private final RabbitTemplate template;

	private  String  broadcast = "_broadcast";

	public PublishProxy(RmqChannel channel) {		
		this.template = new RabbitTemplate(channel.getConnectionFactory());
		this.template.setBeforePublishPostProcessors(message -> {
            message.getMessageProperties().setHeader(EventErrorCode.HEADER_TRACE, MDCUtils.getTraceId());
            return message;
        });
	}

	public int p2p(Object event) {
		String eventName = event.getClass().getName() + "_"+ ManagementFactory.getRuntimeMXBean().getName();
		template.convertAndSend(eventName, eventName, event);
		return EventErrorCode.SUCCEED;
	}

	public int p2p(Object event, final int ttl) {
		String eventName = event.getClass().getName() + "_"+ ManagementFactory.getRuntimeMXBean().getName();
		template.convertAndSend(eventName, eventName, event,
                message -> {
                    message.getMessageProperties().setExpiration(ttl + "");
                    return message;
                });
		return EventErrorCode.SUCCEED;
	}

	public int publish(Object event) {
		String eventName = event.getClass().getName();
		template.convertAndSend(eventName, eventName, event);
		return EventErrorCode.SUCCEED;
	}
	
	public int publish(String eventName,Object event) {
		template.convertAndSend(eventName, eventName, event);
		return EventErrorCode.SUCCEED;
	}
	
	 public int publish(Object event, final int ttl) {
	        String eventName = event.getClass().getName();
	        template.convertAndSend(eventName, eventName, event, message -> {
                message.getMessageProperties().setExpiration(ttl + "");
                return message;
            });
	        return EventErrorCode.SUCCEED;
	    }

	    public int broadcast(Object event) {
	        String eventName = event.getClass().getName();
	        template.convertAndSend(eventName + broadcast, eventName, event);
	        return EventErrorCode.SUCCEED;
	    }

	    public int broadcast(String eventName,Object event) {
	        template.convertAndSend(eventName + broadcast, eventName, event);
	        return EventErrorCode.SUCCEED;
	    }
	    
	    public int broadcast(Object event, final int ttl) {
	        String eventName = event.getClass().getName();
	        template.convertAndSend(eventName + "_broadcast", eventName, event, message -> {
                message.getMessageProperties().setExpiration(ttl + "");
                return message;
            });
	        return EventErrorCode.SUCCEED;
	    }
}
